package io.renren.modules.common.controller;

import io.renren.common.exception.ErrorCode;
import io.renren.common.utils.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Api(tags = "通用方法")
@Slf4j
public class CommonController {
    @Value("${chyBlog.filePath}")
    private String filePath;

    @Value("${chyBlog.imgPath}")
    private String imgPath;

    @Value("${chyBlog.videoPath}")
    private String videoPath;

    /**
     * 文件上传 img file video
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/{type}")
    public Result<HashMap<String, String>> upload(@PathVariable String type, MultipartFile file) {
        if (file == null) {
            new Result().error(ErrorCode.FILE_ERROR, "文件不存在！");
        }
        String basePath = "";
        switch (type) {
            case "file":
                basePath = filePath;
                break;
            case "img":
                basePath = imgPath;
                break;
            case "video":
                basePath = videoPath;
                break;
            default:
                new Result().error(ErrorCode.FILE_ERROR, "不存在的文件类型！");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID() + suffix;
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        try {
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HashMap<String, String> fileObj = new HashMap<>();
        fileObj.put("url", filename);
        return new Result<HashMap<String, String>>().ok(fileObj);
    }

    @GetMapping("/download/{type}")
    public void download(String name, @PathVariable String type, HttpServletResponse response) {
        try {
            String basePath = "";
            switch (type) {
                case "file":
                    basePath = filePath;
//                    response.setContentType("application/*");
                    break;
                case "img":
                    basePath = imgPath;
                    response.setContentType("image/jpeg");
                    break;
                case "video":
                    basePath = videoPath;
                    response.setContentType("video/mp4");
                    break;
                default:
                    new Result().error(ErrorCode.FILE_ERROR, "不存在的文件类型！");
            }
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(basePath + name);
            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}